﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace cc2530.Lib
{
    public class TransationBase : EventArgs
    {
        public byte[] data;
        public int datalen;

        public TransationBase() { data = null; datalen = 0; }

        public TransationBase DeepClone() {
            TransationBase b = new TransationBase();
            b.datalen = this.datalen;
            b.data = new byte[this.datalen];
            Array.Copy(this.data, 0, b.data, 0, b.datalen);
            return b;
        }
    }


    public class Ulitily
    {


        /// <summary>
        /// 显示回调函数
        /// </summary>
        /// <param name="text"></param>
        public delegate void DisplayTextCallBack(string text);

        /// <summary>
        /// 收发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public delegate void OnTransferHandler(object sender, TransationBase args);

        /// <summary>
        /// 修改通道数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public delegate TransationBase OnTransationHandler(object sender, TransationBase args);


        public delegate void onBorderRouterConnect(object sender, contiki.contikiNode BorderRouter);

        /// <summary>
        /// 共享类，一些常用的方法
        /// </summary>
        public class ShareClass
        {
            #region 字符串转换
            /// <summary>
            /// byte[] 转 字符串 0x11-->"00010001"
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            public static string ByteArrayToString2(byte[] data)
            {
                if (data == null) return null;
                try
                {
                    byte[] b = data;
                    int left = 0;
                    int index = 0;
                    StringBuilder str = new StringBuilder();
                    foreach (byte bs in b)
                    {
                        str.Append(Convert.ToString(bs, 2));
                        left = str.Length % 8;
                        index = left;

                        if (left != 0)
                        {
                            left = 8 - left;
                            while (left > 0)
                            {
                                str.Insert(str.Length - index, '0');
                                left--;
                            }
                        }
                        //str.Append(Inter.toBinaryString(bs));//转换为二进制  
                    }
                    return str.ToString();
                }
                catch { return null; }
            }
            /// <summary>
            /// 二进制字符串 to byte[] "11110000"-->0xF0
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public static byte[] String2ToByteArray(string str)
            {
                if (str == null) return null;
                str = str.Replace(" ", "");

                int left = 8 - str.Length % 8;
                StringBuilder strBuilder = new StringBuilder(str);
                //补0
                while (left > 0)
                {
                    strBuilder.Append("0");
                    left--;
                }

                left = 0;

                byte[] result = new byte[strBuilder.ToString().Length / 8];
                result.Initialize();
                foreach (char c in strBuilder.ToString())
                {
                    switch (c)
                    {
                        case '1':
                        case '0':
                            break;
                        default: return null;
                    }

                    result[left / 8] += (byte)(((byte)(c == '1' ? 1 : 0)) << (7 - left % 8));

                    left++;

                }

                return result;

            }


            /// <summary>
            /// 字符串转16进制字节数组
            /// </summary>
            /// <param name="hexString"></param>
            /// <returns></returns>
            public static byte[] strToToHexByteArray(string hexString)
            {
                hexString = hexString.Replace(" ", "");
                hexString = hexString.Replace("\r", "");
                hexString = hexString.Replace("\n", "");
                if ((hexString.Length % 2) != 0)
                    hexString += "0";
                byte[] returnBytes = new byte[hexString.Length / 2];
                for (int i = 0; i < returnBytes.Length; i++)
                    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                return returnBytes;
            }

            /// <summary>
            /// 数组转字符串
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            public static string hexByteArrayToString(byte[] data)
            {
                return BitConverter.ToString(data);
            }

            public static string hexByteArrayToString(byte[] data ,int len)
            {
                    if(len <=0 || data ==null)return null;
                    else{
                        byte[] datainput = new byte[len];
                        Array.Copy(data, datainput, len);
                        return hexByteArrayToString(datainput);
                    }
            }

            public static string hexByteArrayToString(byte[] data, int offset, int len) {
                if (len <= 0 || data == null) return null;
                if (offset + len > data.Length) len = data.Length - offset;
                byte[] d = new byte[len];
                Array.Copy(data, offset, d, 0, d.Length);
                return hexByteArrayToString(d);
            }


            #endregion

            #region IP address
            /// <summary>
            /// 反转,data[] = {11,1,168,192}===>return 0xC0A0010B
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            public static UInt32 ReverseUInt32(byte[] data) {
                if (data == null || data.Length < 4) return 0;
                UInt32 tmp = data[3]; tmp <<= 8;
                tmp += data[2]; tmp <<= 8;
                tmp += data[1]; tmp <<= 8;
                tmp += data[0];
                return tmp;
            }

            /// <summary>
            /// 反转,0xC0A0010B===>data[] = {11,1,168,192}
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            public static byte[]  ReverseAddress(UInt32 address)
            {
                byte[] addr = new byte[4];
                addr[0] = (byte) address;
                addr[1] = (byte)(address >> 8);
                addr[2] = (byte)(address >> 16);
                addr[3] = (byte)(address >> 24);
                return addr;
            }
            #endregion



            #region 校验和

            /// <summary>
            /// 以16 位为单位计算 data 的检验各，用来icmp tcp 检验计算,摘自 contiki kernel
            /// </summary>
            /// <param name="data"></param>
            /// <param name="len"></param>
            /// <returns></returns>
            public static UInt16 CheckSum16(UInt16 sum,byte[] data, int len) {

                int dataptr;
                int last_byte;
                UInt16 t;
                dataptr = 0;
                last_byte = len - 1;

                while (dataptr < last_byte)
                {   /* At least two more bytes */
                    t = (UInt16)((data[0 + dataptr] << 8) + data[1 + dataptr]);
                    sum += t;
                    if (sum < t)
                    {
                        sum++;      /* carry */
                    }
                    dataptr += 2;
                }

                if (dataptr == last_byte)
                {
                    t = (UInt16)((data[0 + dataptr] << 8) + 0);
                    sum += t;
                    if (sum < t)
                    {
                        sum++;      /* carry */
                    }
                }

                /* Return sum in host byte order. */
                return sum;
            }

            #endregion


        }

    }
}

